package com.lyl.mallcloud.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyl.mallcloud.mapper.*;
import com.lyl.mallcloud.pojo.*;
import com.lyl.mallcloud.service.IOrdersService;
import com.lyl.mallcloud.service.ISourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: Liyunlong
 * @Date: 2024/05/12/13:03
 * @Description:
 */

@RestController
@RequestMapping("/echart")
@Slf4j
public class WorkSpaceController {

    @Autowired
    UsersMapper usersMapper;

    @Autowired
    ProductsMapper productsMapper;

    private static final String USER_ONLINE = "user:oline";
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    ProductViewsMapper productViewsMapper;

    @Autowired
    IOrdersService iOrdersService;

    @Autowired
    UserSourceMapper userSourceMapper;

    @Autowired
    SourceMapper sourceMapper;

    @Autowired
    ISourceService sourceService;

    @Autowired
    UserVisitsMapper userVisitsMapper;


    @Autowired
    VisitDatumMapper visitDatumMapper;

    @GetMapping("/work")
    public Result getWorkStats() {
        WorkStats workStats = new WorkStats();
        // 查询注册会员数
        int count = usersMapper.userCount();
        // 平台总商品数
        long total = productsMapper.productCount();
        // 商品销售总量
        long sum = ordersMapper.productSum();
        // 平台销售总额
        long moneySum = ordersMapper.moneySum();
        moneySum = Math.toIntExact((moneySum != 0) ? moneySum : 0L);
        // 在线数量 管理员
        Long size = redisTemplate.opsForSet().size(USER_ONLINE);
        moneySum = moneySum / 10000;
        workStats.setUserCount((long) count);
        workStats.setProductCount(total);
        workStats.setProductSum(sum);
        workStats.setMoney(moneySum);
        workStats.setVipCount(size);
        return Result.success(workStats);
    }


    @GetMapping("/getChartData")
    public ChartData getChartData() {


        List<Integer> productIds = iOrdersService.getTopFiveProductIdsBySales();

        List<Products> salesProductList = new ArrayList<>(productIds.size());
        for (Integer productId : productIds) {
            Products products = productsMapper.selectById(productId);
            if (products != null) {
                salesProductList.add(products);
            }
        }
        int[] visits = new int[productIds.size()];
        for (Integer productId : productIds) {
            if (productId != null) {
                Integer viewsCountSum = productViewsMapper.getViewsCountSum(productId);
                if (viewsCountSum == null) {
                    viewsCountSum = 0;
                }
                visits[productIds.indexOf(productId)] = viewsCountSum;
            }
        }

        String[] categories = salesProductList.stream().
                map(Products::getProductName).toArray(String[]::new);
        int[] stock = salesProductList.stream().mapToInt(Products::getStock).toArray();
        return new ChartData(categories, visits, stock);
    }


    @GetMapping("/visitCounts")
    public ResponseEntity<String> getVisitCounts() {
        // List<Map<String, Object>> rawCounts = productsMapper.countVisits();
        List<Map<String, Object>> rawCounts = productViewsMapper.countVisits();
        if (rawCounts == null || rawCounts.isEmpty()) {
            return ResponseEntity.status(404).body("没有足够的访问数据");
        }
        List<VisitCount> visitCountList = new ArrayList<>();
        List<String> legendData = new ArrayList<>();
        for (Map<String, Object> countMap : rawCounts) {
            if (countMap != null && countMap.containsKey("view_range") && countMap.containsKey("count")) {
                String viewRange = (String) countMap.get("view_range");
                long count = (long) countMap.get("count");
                if (viewRange != null) {
                    legendData.add(viewRange);
                    visitCountList.add(new VisitCount(viewRange, count));
                }
            }
        }
        VisitCounts visitCounts = new VisitCounts();
        visitCounts.setLegendData(legendData);
        visitCounts.setData(visitCountList);
        try {
            return ResponseEntity.ok(JSONUtil.toJsonStr(visitCounts));
        } catch (Exception e) {
            log.error("", e);
            return ResponseEntity.status(500).body("系统错误");
        }
    }

    @GetMapping("/api/data2")
    public List<Object> getData() {
        return Arrays.asList(Arrays.asList("1月", "2月", "3月", "4月", "5月", "6月"),
                // 销售量数据
                Arrays.asList(320, 332, 301, 334, 390, 330),
                // 访问量数据
                Arrays.asList(820, 932, 901, 934, 1290, 1330));
    }

    @GetMapping("/data")
    public List<Object> getData2() {
        // 查询每月的销售量
        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        ordersQueryWrapper.orderByAsc("order_date");
        List<Orders> orders = ordersMapper.selectList(ordersQueryWrapper);
// 查询每月的访问量
        QueryWrapper<ProductViews> viewsQueryWrapper = new QueryWrapper<>();
        viewsQueryWrapper.orderByAsc("view_time");
        List<ProductViews> views = productViewsMapper.selectList(viewsQueryWrapper);
// 使用 distinct() 去除重复的月份
        Integer[] months = orders.stream().map(Orders::getOrderDate)
                .map(LocalDateTime::getMonthValue).distinct().toArray(Integer[]::new);
        // 分组并计算每月的销售量总和
        Map<Integer, Integer> monthlySales = orders.stream()
                .collect(Collectors.groupingBy(order -> order.getOrderDate()
                        .getMonthValue(), Collectors.summingInt(Orders::getQuantity)));
        int[] salesValues = new int[monthlySales.size()];
        int index = 0;
        for (int salesTotal : monthlySales.values()) {
            salesValues[index++] = salesTotal;
        }
        // 分组并计算每月的访问量总和
        Map<Integer, Integer> monthlyViews = views.stream().
                collect(Collectors.groupingBy(view -> view.getViewTime().
                        getMonthValue(), Collectors.summingInt(ProductViews::getViewsCount)));
        int[] monthlyView = new int[monthlyViews.size()];
        int index2 = 0;
        for (int monthlyView2 : monthlyViews.values()) {
            monthlyView[index2++] = monthlyView2;
        }
        return Arrays.asList(months, salesValues, monthlyView);
    }


    @GetMapping("/userSources")
    public ResponseEntity<String> getUserSources() {
        List<Map<String, Object>> result = userSourceMapper.selectBySource();
        List<String> sourceNames = new ArrayList<>();
        List<Long> userCounts = new ArrayList<>();
        List<VisitCount> visitCountList = new ArrayList<>();
        for (Map<String, Object> row : result) {
            sourceNames.add((String) row.get("source_name"));
            userCounts.add((Long) row.get("total_users"));
            visitCountList.add(new VisitCount((String) row.get("source_name"),
 (Long) row.get("total_users")));
        }
        VisitCounts visitCounts = new VisitCounts();
        visitCounts.setLegendData(sourceNames);
        visitCounts.setData(visitCountList);
        try {
            return ResponseEntity.ok(JSONUtil.toJsonStr(visitCounts));
        } catch (Exception e) {
            log.error("JSON转换失败", e);
            return ResponseEntity.status(500).body("系统错误");
        }
    }
    @GetMapping("/weeklyVisitData")
    public List<VisitDatum> getWeeklyVisitData() {
        // 调用Mapper方法获取近7天的访问数据
        return visitDatumMapper.getWeeklyVisitData();
    }
}
